package com.yxp423.ssmempl.controller;

import cn.hutool.core.util.ObjectUtil;

import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.dto.NotifyDto;
import com.yxp423.ssmempl.service.INotifyService;
import com.yxp423.ssmempl.service.WebSocketService;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-06-13 11:24
 * @Version: 1.0
 */

@Controller
@RequestMapping("/notify")
@Slf4j
@Api(tags = "通知管理")
public class NotifyController {

	@Autowired
	INotifyService notifyService;
	@Autowired
	WebSocketService webSocket;


	@GetMapping("/addnotify")
	public String toNotifyPage() {


		return "notify/addNotify";
	}


	@PostMapping("/")
	@ResponseBody
	@ApiOperation("添加通知")

	public AjaxResult addNotify( @ApiParam("实体对象") NotifyDto notifyDto) {

		AjaxResult result = new AjaxResult();

		try {
			User user = (User) SecurityUtils.getSubject().getPrincipal();

			if (ObjectUtil.isNull(user)){
				result.setSuccess(false);
				result.setMsg("请登录");
				return result;
			}

//			String jsonString = JSONUtil.toJsonPrettyStr(notifyDto);
			webSocket.sendToAll(notifyDto.getNotifyContext());

			int flag = notifyService.saveNotify(notifyDto, user);

			if (flag>0){
				result.setSuccess(true);
				result.setMsg("添加成功");
				result.setStatusCode("201");
			}else {
				result.setSuccess(false);
				result.setMsg("添加失败");
				result.setStatusCode("501");
			}

		} catch (Exception e) {

			log.error("发生错误，{}",e.getMessage());

		}


		return result;
	}

}
